package domain.searchEngine.compass;

import org.compass.core.Compass ;
import org.compass.core.CompassSession ;
import org.compass.core.config.CompassConfiguration ;
import org.compass.core.config.CompassConfigurationFactory ;
import org.compass.core.engine.SearchEngineIndexManager ;
import org.compass.gps.CompassGpsDevice ;
import org.compass.gps.device.hibernate.HibernateGpsDevice ;
import org.compass.gps.impl.SingleCompassGps ;

import persistence.hibernate.HibernatePersistenceFactory ;
import domain.ForumData ;
import domain.message.Post ;
import domain.searchEngine.IndexAgent ;
import domain.searchEngine.SearchEngine ;
import domain.searchEngine.SearchEngineFactory ;
import domain.user.Login ;

/**
 * builds components for searching using Compass.
 *
 * @author idan
 */
public class CompassSearchEngineFactory implements SearchEngineFactory
{
	private CompassSession compassSession ;

	private ForumData forumData ;

	/**
	 * @param hibernate persistence builder to which compass can connect its sessions.
	 * @param forumData data from which search results are retrieved.
	 */
	public CompassSearchEngineFactory(final HibernatePersistenceFactory hibernate, final ForumData forumData)
	{
		super() ;
		this.forumData = forumData ;

		CompassConfiguration conf = CompassConfigurationFactory.newConfiguration().setConnection("tests/data/compass") ;
		conf.addClass(Post.class);
		conf.addClass(Login.class) ;
		Compass compass = conf.buildCompass() ;

		if (!hibernate.loadingFromExisting())
		{
			SearchEngineIndexManager indexManager = compass.getSearchEngineIndexManager() ;
			indexManager.cleanIndex() ;
		}

		SingleCompassGps gps = new SingleCompassGps(compass);
		CompassGpsDevice hibernateDevice = new HibernateGpsDevice("hibernate", hibernate.getSessionFactory());
		gps.addGpsDevice(hibernateDevice);
		gps.start();
		this.compassSession = compass.openSession() ;
	}

	/**
	 * @return the compass session.
	 */
	public CompassSession getCompassSession()
	{
		return this.compassSession ;
	}

	/**
	 * @see domain.searchEngine.SearchEngineFactory#getIndexAgent()
	 */
	public IndexAgent getIndexAgent(){
		return new CompassIndexAgent() ;
	}

	/**
	 * @see domain.searchEngine.SearchEngineFactory#getSearchEngine()
	 */
	public SearchEngine getSearchEngine(){
		return new CompassSearchEngine(this.compassSession, this.forumData) ;
	}

}
